import re

from rest_framework import serializers
from .models import User, Address, Role
from django_redis import get_redis_connection
# from rest_framework_jwt.settings import api_settings
from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""
    # 序列化器的所有字段：[id,username,password,password2,mobile,sms_code,allow]
    # 需要校验的字段：[username,password,password2,mobile,sms_code,allow]
    # 需要序列化的字段： [id,username,mobile]
    # 需要反序列化的字段： [username,password,password2,mobile,sms_code,allow]
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    # allow = serializers.CharField(label='同一协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)
    success = serializers.BooleanField(label='是否成功登录', read_only=True)

    class Meta:
        model = User  # 从user映射序列化器字段

        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'token', 'success']
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的⽤户名',
                    'max_length': '仅允许5-20个字符的⽤户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """单独校验手机号"""
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式有误')
        return value

    # def validate_allow(self, value):
    #     """是否同意协议"""
    #     if value != 'true':
    #         raise serializers.ValidationError('请同意用户协议')
    #     return value

    def validate(self, attrs):
        """检验两个密码是否一致"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两个密码不一致')
        # 校验验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None or attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误')
        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        # del validated_data['allow']
        del validated_data['sms_code']
        password = validated_data.pop('password')
        # 创建用户模型对象，给模型中的mobile和username赋值
        user = User(**validated_data)
        user.set_password(password)  # 把加密的密码赋值给user的password属性
        user.save()
        refresh = RefreshToken.for_user(user)
        access_token = str(refresh.access_token)
        user.token = access_token
        user.success = True
        return user


# class AdminUserSerializers(serializers.ModelSerializer):
#     class Meta:
#         model = User
#         fields = ['id', 'username', 'roles', 'mobile', 'sms_code', 'token', 'success']


class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        # fields = ['id', 'name']
        fields = ['name']


class UserSerializer(serializers.ModelSerializer):
    roles = RoleSerializer(many=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'roles', 'date_joined', 'mobile', 'is_active']


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class adminUserDetailSerializer(serializers.ModelSerializer):
    roles = RoleSerializer(many=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'roles', 'date_joined', 'is_active']


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class MyTokenSerializer(TokenObtainPairSerializer):

    @classmethod
    def get_token(cls, user):
        """
        此方法往token的有效负载 payload 里面添加数据
        若自定义了用户表，可以在这里面添加用户邮箱，性别，年龄等可以公开的信息
        这部分放在token里面是可以被解析的，所以不要放比较私密的信息
        :param user: 用戶信息
        :return: token
        """
        token = super().get_token(user)
        # 添加个人信息
        token['name'] = user.username
        # token['mobile'] = user.mobile
        return token

    def validate(self, attrs):
        '''此方法是响应数据结构，默认返回只有 access 和 refresh'''
        data = super().validate(attrs=attrs)
        # 获取Token对象
        refresh = self.get_token(self.user)
        data.pop('refresh')
        data.pop('access')
        roles = self.user.roles.values_list('name', flat=True)
        success = True
        data['success'] = success
        content = {
            'username': self.user.username,
            'roles': list(roles),
            'accessToken': str(refresh.access_token),
            'refreshToken': str(refresh),
            'expires': refresh.access_token.payload['exp']
        }
        data['data'] = content
        return data


class MyrefreshTokenSerializer(TokenObtainPairSerializer):

    @classmethod
    def get_token(cls, user):
        """
        此方法往token的有效负载 payload 里面添加数据
        若自定义了用户表，可以在这里面添加用户邮箱，性别，年龄等可以公开的信息
        这部分放在token里面是可以被解析的，所以不要放比较私密的信息
        :param user: 用戶信息
        :return: token
        """
        token = super().get_token(user)
        # 添加个人信息
        token['name'] = user.username
        # token['mobile'] = user.mobile
        return token

    def validate(self, attrs):
        '''此方法是响应数据结构，默认返回只有 access 和 refresh'''
        data = super().validate(attrs=attrs)
        # 获取Token对象
        refresh = self.get_token(self.user)
        data.pop('refresh')
        data.pop('access')
        success = True
        data['success'] = success
        content = {
            'accessToken': str(refresh.access_token),
            'refreshToken': str(refresh),
            'expires': refresh.access_token.payload['exp']
        }
        data['data'] = content
        return data


class RefreshTokenSerializer(serializers.Serializer):
    accessToken = serializers.CharField(required=False)
    refreshToken = serializers.CharField(required=True)
    expires = serializers.DateTimeField(required=False)

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

    def validate_refreshToken(self, value):
        try:
            refresh = RefreshToken(value)
            refresh.verify()
        except Exception as e:
            raise serializers.ValidationError(str(e))
        return refresh

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['expires'] = instance['expires'].strftime('%Y/%m/%d %H:%M:%S')
        return representation
